/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
*/

package com.jinhe.tss.core.cachepool.extend.thread;

import org.apache.log4j.Logger;

import com.jinhe.tss.core.cachepool.CacheManager;
import com.jinhe.tss.core.cachepool.Cacheable;
import com.jinhe.tss.core.cachepool.IArithmetic;
import com.jinhe.tss.core.cachepool.TimeWrapper;
import com.jinhe.tss.core.cachepool.strategy.CacheConstants;


/** 
 * <p> ThreadPoolArithmetic.java </p> 
 * 
 * 线程池算法类。
 * 创建、验证、销毁工作线程。
 * 
 * @author Jon.King 2007-1-9
 */

public class ThreadPoolArithmetic implements IArithmetic{
    
    protected Logger log = Logger.getLogger(this.getClass());
  
    public Cacheable create(Long cyclelife){
        IThreadPool tPool = (IThreadPool) CacheManager.getInstance().getCachePool(CacheConstants.THREAD_POOL);
        Thread thread = tPool.createWorkThread();
        thread.start();
        return new TimeWrapper(thread.getName(), thread, cyclelife);
    }

    public boolean isValid(Cacheable o){
        return ((Thread)o.getValue()).isAlive(); 
    }

    public void destroy(Cacheable o){
        Thread poolWorker = (Thread)o.getValue();
        try {
            poolWorker.join(50); //等待线程死亡
        } catch (InterruptedException e) {
            log.error("停止initer线程时被中断", e);
        }
        poolWorker = null;
    }
}

